package uzpay

import (
	"encoding/json"
	"errors"

	"gitee.com/liuxuezhan/ar-platform/pay-channel-packet/uzpay/uzpay/tool"
)

type WithdrawResp struct {
	RespCode       string `json:"respCode"`
	ErrorMsg       string `json:"errorMsg"`
	SignType       string `json:"signType"`
	Sign           string `json:"sign"`
	NchId          string `json:"mchId"`
	MerTransferId  string `json:"merTransferId"`
	TransferAmount string `json:"transferAmount"`
	ApplyDate      string `json:"applyDate"`
	TradeNo        string `json:"tradeNo"`
	TradeResult    string `json:"tradeResult"`
}
type PayResp struct {
	RespCode    string `json:"respCode"`
	TradeMsg    string `json:"tradeMsg"`
	SignType    string `json:"signType"`
	Sign        string `json:"sign"`
	NchId       string `json:"mchId"`
	MchOrderNo  string `json:"mchOrderNo"`
	OriAmount   string `json:"oriAmount"`
	TradeAmount string `json:"tradeAmount"`
	OrderDate   string `json:"orderDate"`
	OrderNo     string `json:"orderNo"`
	TradeResult string `json:"tradeResult"`
	PayInfo     string `json:"payInfo"`
}

type BalanceResp struct {
	Status    int    `json:"status"`
	Timestamp int64  `json:"timestamp"`
	Msg       string `json:"msg"`
	Balance   string `json:"balance"` // 余额
	Params    string `json:"params"`
}

// 代收（付款）UzPay
func UzPay(tempParams map[string]any) (resp PayResp, err error) {
	// 请求第三方接口
	params := make(map[string]any)
	params["version"] = "1.0"
	params["mch_id"] = tempParams["mid"]
	params["notify_url"] = tempParams["NotifyUrl"]
	params["mch_order_no"] = tempParams["orderID"]
	params["pay_type"] = tempParams["payType"]
	params["trade_amount"] = tempParams["amount"]
	params["order_date"] = tempParams["orderDate"]
	if _, exists := tempParams["bankCode"]; exists {
		params["bank_code"] = tempParams["bankCode"]
	}
	if _, exists := tempParams["goodsName"]; exists {
		params["goods_name"] = tempParams["goodsName"]
	}
	if _, exists := tempParams["payerEmail"]; exists {
		params["payer_email"] = tempParams["payerEmail"]
	}
	if _, exists := tempParams["payerName"]; exists {
		params["payer_name"] = tempParams["payerName"]
	}
	if _, exists := tempParams["payerPhone"]; exists {
		params["payer_phone"] = tempParams["payerPhone"]
	}
	if _, exists := tempParams["payerCard"]; exists {
		params["payer_card"] = tempParams["payerCard"]
	}
	if v, err := tool.GenerateSignature(params, tempParams["SecretKey"].(string)); err != nil {
		return resp, errors.New("ErrSignGenerateFailed")
	} else {
		params["sign_type"] = "MD5"
		params["sign"] = v
	}
	output, err := tool.SendPostFormUrlEncoded(tempParams["url"].(string), params)

	if err != nil {
		return resp, err
	}
	var result PayResp
	err = json.Unmarshal([]byte(output), &result)
	if err != nil {
		return resp, err
	}
	if result.RespCode != "SUCCESS" {
		return resp, errors.New(result.TradeMsg)
	}
	return result, nil
}

// 代付（提现）Withdraw
func Withdraw(url, mid, orderId, amount, orderDate, bankCode, receiveName, receiveAccount, remark, NotifyUrl, SecretKey string) (resp WithdrawResp, err error) {
	// 请求第三方接口
	params := make(map[string]any)
	params["mch_id"] = mid
	params["mch_transferId"] = orderId
	params["transfer_amount"] = amount
	params["apply_date"] = orderDate
	params["bank_code"] = bankCode
	params["receive_name"] = receiveName
	params["receive_account"] = receiveAccount
	params["back_url"] = NotifyUrl
	if remark != "" {
		params["remark"] = remark
	}
	if v, err := tool.GenerateSignature(params, SecretKey); err != nil {
		return resp, errors.New("ErrSignGenerateFailed")
	} else {
		params["sign"] = v
		params["sign_type"] = "MD5"
		params["key"] = SecretKey
	}
	output, err := tool.SendPostFormUrlEncoded(url, params)

	if err != nil {
		return resp, err
	}
	var result WithdrawResp
	err = json.Unmarshal([]byte(output), &result)
	if err != nil {
		return resp, err
	}
	if result.RespCode != "SUCCESS" {
		return resp, errors.New(result.ErrorMsg)
	}
	return result, nil
}
